package com.java.digitalsignagesystem.config;


import com.java.digitalsignagesystem.entity.Result;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.annotation.Resource;
import javax.security.auth.login.AccountExpiredException;
import javax.servlet.MultipartConfigElement;
import java.nio.file.AccessDeniedException;


/**
 * 全局异常解析
 *
 * @author youlinaixu
 * @date 2024/03/13
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error(500, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAuthorizationException(AccessDeniedException e) {
        log.error(e.getMessage());
        return Result.error(500, "没有权限，请联系管理员授权");
    }

    @ExceptionHandler(AccountExpiredException.class)
    public Result handleAccountExpiredException(AccountExpiredException e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result illegalHandler(IllegalArgumentException e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Result.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        //log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.error(message);
    }

//    /**
//     * 演示模式异常
//     */
//    @ExceptionHandler(RuntimeException.class)
//    public Result demoModeException(RuntimeException e) {
//        return Result.error("演示模式，不允许操作");
//    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        StringBuffer sb = new StringBuffer();
        sb.append("不支持");
        sb.append(e.getMethod());
        sb.append("请求方法，");
        String[] methods = e.getSupportedMethods();
        if (methods != null) {
            sb.append("支持：");
            for (int i = 0; i < methods.length; i++) {
                sb.append(methods[i]);
                if (i < methods.length - 1) {
                    sb.append("、");
                }
            }
        } else {
            sb.append("无可用请求方式。");
        }
        log.error(sb.toString(), e);
        return Result.error(405, sb.toString());
    }

    @Resource
    MultipartConfigElement configElement;

    @ExceptionHandler(SizeLimitExceededException.class)
    public Result SizeLimitExceededException(SizeLimitExceededException e) {


        StringBuffer sb = new StringBuffer();
        sb.append("文件大小超过" + configElement.getMaxFileSize() / 1024 / 1024 + "MB");
        log.error(sb.toString(), e);
        return Result.error(500, sb.toString());
    }
}
